package com.zhanglinfeng.gateway.yuekaogateway.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;

@Slf4j
//@Component
public class AuthFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String token = request.getHeaders().getFirst("token");
        log.info("token:{}", token);
//        exchange.mutate().
        if (StringUtils.isEmpty(token) /*|| jwtUtils.validate(token)*/) {
            //设置编码，防止浏览器乱码
            response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
            //设置http状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //设置返回结果信息
            HashMap<String, Object> result = new HashMap<>();
            result.put("code", 401);
            result.put("msg","登录过期或失效");
            DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONString(result).getBytes());
            return response.writeWith(Flux.just(dataBuffer));
        }
        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
